<template>
  <el-upload
    v-model:file-list="fileList"
    :http-request="onUploadFile"
    v-bind="$attrs"
    list-type="picture-card"
    :on-preview="handlePictureCardPreview"
    :on-remove="handleRemove"
    :on-exceed="handleExceed"
    :class="{ disabled: hiddenCard && fileList.length >= limit }"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="dialogImageUrl" alt="Preview Image" />
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, watchEffect, useAttrs, computed } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { uploadFile } from "@/api/common";
import {
  type UploadProps,
  type UploadUserFile,
  type UploadRequestHandler,
  ElMessage
} from "element-plus";

const attrs = useAttrs();
// 直接获取 limit，若未提供，则默认为 0
const limit = computed(() => Number(attrs.limit) || 0);
const { hiddenCard } = defineProps({
  hiddenCard: {
    type: Boolean,
    default: false
  }
});

const fileListProp = defineModel<UploadUserFile[]>();
const fileList = ref<UploadUserFile[]>([]);

watchEffect(() => {
  fileList.value = fileListProp.value;
});
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const onUploadFile: UploadRequestHandler = async options => {
  const { file, onSuccess, onError } = options;
  const formData = new FormData();
  formData.append("file", file);
  try {
    const res = await uploadFile(formData);
    console.log(res);
    fileListProp.value = [
      { url: res.data.fullPath, name: file.name, uid: file.uid }
    ];
    onSuccess(res);
  } catch (error) {
    onError(error);
  }
};
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview: UploadProps["onPreview"] = uploadFile => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  console.log(files, uploadFiles);
  ElMessage.warning("只能上传一张图片");
};
</script>
<style scoped lang="scss">
.disabled .el-upload--picture-card {
  display: none;
}
</style>
